<template>
	<view class="tool">
		<!-- 图片上传 -->
		<view v-for="(item, index) in fileList" :key="index" class="preview-item">
		  <!-- 图片预览 -->
		  <image
		    v-if="item.fileType === 'image'"
		    :src="item.url || item.thumb"
		    mode="aspectFill"
		    class="preview-image"
		  />
		  <!-- 视频预览 -->
		  <video
		    v-else-if="item.fileType === 'video'"
		    :src="item.url"
		    controls
		    class="preview-video"
		  />
		  <!-- 删除按钮 -->
		  <view class="delete-btn" @click="deletePic({index})"></view>
		</view>
		<uv-upload name="1" :multiple="multiple" :deletable="!disabled" :fileList="[]" :maxCount="maxImageCount"
			:disabled="disabled" @afterRead="handleImageUpload" @delete="deletePic" v-if="imageCount<props.maxImageCount">
			<view class="addImg">
				<uv-icon name="camera" color="#303133" size="40" />
				<text>还可添加{{props.maxImageCount-imageCount}}张</text>
			</view>
		</uv-upload>
		
		<!-- 视频上传 -->
		<uv-upload name="2" :multiple="false" :deletable="!disabled" :fileList="[]" :maxCount="maxVedioCount"
			:disabled="disabled" @afterRead="handleVideoUpload" @delete="deletePic" accept="video" v-if="videoCount<props.maxVedioCount">
			<view class="addImg">
				<uv-icon name="https://linshitong.oss-cn-shenzhen.aliyuncs.com/dev/image/2025/0816/59fb2202508161150163613.png" size="40" />
				<text>添加短视频</text>
			</view>
		</uv-upload>
	</view>
</template>
<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue';
	import {
		uploadImage,
		videoUpload
	} from '@/api'

	const emit = defineEmits(['success'])

	const props = defineProps({
		multiple: {
			type: Boolean,
			default: false
		},
		maxImageCount: {
			type: Number,
			default: 1
		},
		maxVedioCount: {
			type: Number,
			default: 1
		},
		width: {
			type: [Number, String],
			default: 80
		},
		height: {
			type: [Number, String],
			default: 80
		},
		list: {
			type: [Array, String],
			default: []
		},
		disabled: {
			type: Boolean,
			default: false
		}
	})

	const init = ref(false)
	const fileList = ref([])
	// 计算属性
	const imageCount = computed(() => fileList.value.filter(item => item.fileType === 'image').length);
	const videoCount = computed(() => fileList.value.filter(item => item.fileType === 'video').length);
	const handleImageUpload = async (event) => {
		if (imageCount.value >= props.maxImageCount) {
			uni.showToast({
				title: `最多上传 ${props.maxImageCount} 张图片`,
				icon: 'none'
			});
			return;
		}
		let lists = [].concat(event.file)
		lists.map((item) => {
			fileList.value.push({
				...item,
				fileType: 'image',
				message: '上传中',
				status: 'uploading',
			})
		})
		await upImg()
		emit('success', fileList.value)
	}
	
	const upImg = async () => {
		return new Promise(async (resolve, reject) => {
			for (let i = 0; i < fileList.value.length; i++) {
				if (fileList.value[i].status === 'uploading' && fileList.value[i].fileType === 'image') {
					const { data } = await uploadImage({
						name: 'file',
						filePath: fileList.value[i].thumb,
					})
					fileList.value[i].src = data
					fileList.value[i].status = 'success'
					fileList.value[i].message = '上传成功'
				}
			}
			resolve()
		})
	}
	
	const handleVideoUpload = async (event) => {
		let lists = [].concat(event.file)
		// 检查文件大小（不超过 5MB）
		const MAX_SIZE = 5 * 1024 * 1024; // 5MB = 5,242,880 Bytes

		for (const item of lists) {
			// 获取文件大小（字节）
			const fileSize = item.size || 0;

			if (fileSize > MAX_SIZE) {
				uni.showToast({
					title: '文件大小不能超过5MB',
					icon: 'none',
					duration: 2000
				});
				return; // 直接终止上传
			}
		}

		// 如果文件大小符合要求，继续上传
		lists.map((item) => {
			fileList.value.unshift({
				...item,
				fileType: 'video',
				message: '上传中',
				status: 'uploading',
			})
		})
		await upVedio()
		emit('success', fileList.value)
	}

	const upVedio = async () => {
		return new Promise(async (resolve, reject) => {
			for (let i = 0; i < fileList.value.length; i++) {
				if (fileList.value[i].status === 'uploading' && fileList.value[i].fileType === 'video') {
					const {
						data
					} = await videoUpload({
						name: 'file',
						filePath: fileList.value[i].url,
					})
					fileList.value[i].src = data
					fileList.value[i].status = 'success'
					fileList.value[i].message = '上传成功'
				}
			}
			resolve()
		})
	}

	const deletePic = (event) => {
		fileList.value.splice(event.index, 1)
		emit('success', fileList.value)
	}
	
	watch(props, (newVal) => {
		if (init.value) return
		if (typeof props.list === 'string' && props.list) {
			fileList.value = [{
				url: props.list,
				status: 'success',
				fileType: 'image'
			}]
			init.value = true
		}
		if (typeof props.list === 'object' && props.list.length > 0) {
			fileList.value = props.list.map(e => ({
				url: e,
				status: 'success',
				fileType: e.includes('.mp4') ? 'video' : 'image' // 简单类型推断
			}))
			init.value = true
		}
	}, {
		immediate: true,
		deep: true
	})
</script>
<style lang="scss" scoped>
	.tool {
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-start;
		gap: 20upx;
		margin-top: 20upx;
	}
	.uv-upload {
		flex: none!important;
	}
	.addImg {
		display: inline-flex;
		width: 200upx;
		height: 200upx;
		border: #999 1upx dashed;
		align-items: center;
		justify-content: center;
		flex-direction: column;

	
		text {
			color: #303133;
			font-size: 28upx;
		}
	}
	
	.preview-item {
	  position: relative;
	  width: 202upx;
	  height: 202upx;
	  overflow: hidden;
	}
	
	.preview-image, .preview-video {
	  width: 100%;
	  height: 100%;
	  object-fit: cover;
	}
	
	.delete-btn {
	    position: absolute;
	    top: 6px;
	    right: 6px;
	    background: rgba(0, 0, 0, 0.6);
	    width: 24px;
	    height: 24px;
	    border-radius: 50%;
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    cursor: pointer;
	    transition: background 0.2s ease;
	}
	
	.delete-btn:hover {
	    background: rgba(255, 0, 0, 0.8);
	}
	
	/* 使用伪元素创建关闭图标，避免图标字体兼容性问题 */
	.delete-btn::before {
	    content: '×';
	    color: white;
	    font-size: 18px;
	    font-weight: bold;
	}
</style>